#include "Mutex.hpp"
#include <vector>
pthread_mutex_t mtx;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static int ticket = 1000;
void *route(void *args)
{

    auto id = static_cast<char *>(args);
    while (1)
    {
        pthread_mutex_lock(&mtx);

        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sellls ticket:%d\n", id, ticket--);
            pthread_mutex_unlock(&mtx);
        }
        else
        {
            // pthread_mutex_unlock(&mtx);

            std::cout << id << " wait on cond!" << std::endl;
            pthread_cond_wait(&cond, &mtx);

            printf("%s 被叫醒了!!\n", id);
        }
        pthread_mutex_unlock(&mtx);
    }
    return nullptr;
}


int main()
{
    pthread_t threads[4];
    pthread_mutex_init(&mtx, nullptr);
    for (int i = 1; i <= 4; i++)
    {
        std::string name = "thread-" + std::to_string(i);
        std::cout << "thread :" << name << " is created" << std::endl;
        const void *ptr = name.c_str();
        pthread_create(&threads[i - 1], nullptr, route, const_cast<void *>(ptr));
    }

    int cnt = 10;
    while (true)
    {
        sleep(5);
        printf("主线程放票\n");
        ticket += cnt;
        pthread_cond_signal(&cond);
    }

    for (auto &x : threads)
    {
        pthread_join(x, nullptr);
    }
}


// zdl:: 上来我们现在来实现一个小demo
